#pragma once

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include "Sock.hpp"

const static uint16_t defaultport = 8888;

using func_t = std::function<std::string (const std::string&)>; 

class HttpServer;
class ThreadData
{
public:
    ThreadData(int sock, const std::string &ip, const uint16_t &port, HttpServer *hsvrp)
        : _sock(sock), _ip(ip), _port(port), _hsvrp(hsvrp)
    {
    }
    ~ThreadData()
    {
    }

public:
    int _sock;
    std::string _ip;
    uint16_t _port;
    HttpServer *_hsvrp;
};

class HttpServer
{
public:
    HttpServer(func_t func, uint16_t port = defaultport) : _func(func), _port(port)
    {
        
    }

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
    }

    void handlerHttpRequest(int sock)
    {
        char buffer[4096];
        std::string request;
        ssize_t s = recv(sock, buffer, sizeof(buffer)-1, 0);
        if(s > 0)
        {
            buffer[s] = '\0';
            request = buffer;
            std::string response = _func(request);
            send(sock, response.c_str(), response.size(), 0);
        }
        else
        {
            logMessage(Info, "client quit...");
        }
    }

    static void *threadRoutine(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *> (args);
        td->_hsvrp->handlerHttpRequest(td->_sock);
        close(td->_sock);
        delete td;

        return nullptr;
    }

    void Start()
    {
        for( ; ; )
        {
            std::string clientip;
            uint16_t clientport;
            int sock = _listensock.Accept(&clientip, &clientport);
            if(sock < 0)
            {
                continue;
            }

            pthread_t pid;
            ThreadData *td = new ThreadData(sock, clientip, clientport, this);
            pthread_create(&pid, nullptr, threadRoutine, td);

        }
    }

    ~HttpServer() {}

private:
    uint16_t _port;
    Sock _listensock;
    func_t _func;
};